import { Injectable } from '@nestjs/common'
import { PrismaService } from '../prisma/prisma.service'
import { JwtService } from '@nestjs/jwt'
import { LoginDto } from './dto/login.dto'
import { MD5, enc } from 'crypto-js'

@Injectable()
export class LoginService {
    constructor(
        private readonly prisma: PrismaService,
        private readonly jwtService: JwtService
    ) {}

    async login(loginDto: LoginDto) {
        const account = await this.prisma.account.findFirst({
            where: {
                tel: loginDto.tel
            }
        })

		if (account === null) {
			return {
                code: '1001',
                tips: '哦豁，手机号不存在呀，笨蛋！',
                data: null
            }
		}

		const password = MD5(account.password + process.env.SALT).toString(enc.Base64)
		if (loginDto.password !== password) {
			return {
                code: '1002',
                tips: '哦豁，密码错了呀，你不会是盗号的吧？',
                data: null
            }
		}

        if (account.status === 0) {
            return {
                code: '1003',
                tips: '哦豁，该账号被禁用了，哈哈：——',
                data: null
            }
        }
        const token = this.jwtService.sign({
            icoomn: 'YanYunFeng'
        }, {
            secret: process.env.SECRET
        })

        return { token }
    }
}
